package com.ydcloud.${packageName}.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.task.Task;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.codingapi.tx.annotation.TxTransaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hcloud.utils.StringUtil;
import com.hcloud.exception.ServiceException;
import com.hcloud.page.Page;

import com.ydcloud.${packageName}.domain.criteria.${jName}Criteria;
import com.ydcloud.${packageName}.domain.criteria.${jName}Criteria.Criteria;
import com.ydcloud.${packageName}.dao.${jName}Dao;
import com.ydcloud.${packageName}.domain.${jName};
import com.ydcloud.${packageName}.service.${jName}Service;
<#if (bpmnIsGenerate)>
import com.ydcloud.${packageName}.enums.${jName}StatusEnum;
import com.yst.user.domain.UaaUser;
import com.yst.workflow.enums.GlobalVariable;
import com.yst.workflow.enums.CommonProcessRequestParam;
import com.yst.workflow.service.ProcessService;
import com.yst.workflow.enums.ProcessType;
</#if>

/*********************************************************************************************************
 * Copyright (c) 个人
 * All rights reserved.
 *
 * 文件名称:public class ${jName}ServiceImpl{ } 
 * 
 * 摘    要： 
 * 版    本：1.0
 * 作    者：${createBy}
 * 创建于：${createDate}
 * 最后修改时间：
 * 
*********************************************************************************************************/
@Service("${jPname}Service")
public class ${jName}ServiceImpl  implements ${jName}Service {

	@Autowired
	private ${jName}Dao ${jPname}Dao;
	<#if (bpmnIsGenerate)>
	@Autowired
	private ProcessService processService;
	</#if>
	@Override
	public long countByCriteria(${jName}Criteria ${jPname}Criteria) throws ServiceException {
		return ${jPname}Dao.countByCriteria(${jPname}Criteria);
	}
    
    @Override
    public int countPage(Map<String, Object> map) throws ServiceException {
		return ${jPname}Dao.countPage(map);
	}
    
    @Override
    public List<${jName}> queryPageList(Map<String,Object> map) throws ServiceException {
		return ${jPname}Dao.queryPageList(map);
	}

	@Override
    public int deleteByCriteria(${jName}Criteria ${jPname}Criteria) throws ServiceException {
		return ${jPname}Dao.deleteByCriteria(${jPname}Criteria);
	}

	@Override
    public int deleteByPrimaryKey(Long id) throws ServiceException {
		return ${jPname}Dao.deleteByPrimaryKey(id);
	}
 
 	@Override
    public int insert(${jName} ${jPname}) throws ServiceException {
		return ${jPname}Dao.insert(${jPname});
	}
    
    @Override
    public void batchInsert(List<${jName}> ${jPname}List) throws ServiceException {
		 ${jPname}Dao.batchInsert(${jPname}List);
	}

	@Override
    public int insertSelective(${jName} ${jPname}) throws ServiceException {
		return ${jPname}Dao.insertSelective(${jPname});
	}

	@Override
    public List<${jName}> selectByCriteria(${jName}Criteria ${jPname}Criteria) throws ServiceException {
		return ${jPname}Dao.selectByCriteria(${jPname}Criteria);
	}

	@Override
    public ${jName} selectByPrimaryKey(Long id) throws ServiceException {
		return ${jPname}Dao.selectByPrimaryKey(id);
	}

	@Override
    public int updateByCriteriaSelective(${jName} ${jPname}, ${jName}Criteria ${jPname}Criteria) throws ServiceException {
		return ${jPname}Dao.updateByCriteriaSelective(${jPname},${jPname}Criteria);
	}

	@Override
    public int updateByCriteria(${jName} ${jPname},${jName}Criteria ${jPname}Criteria) throws ServiceException {
		return ${jPname}Dao.updateByCriteria(${jPname},${jPname}Criteria);
	}

	@Override
    public int updateByPrimaryKeySelective(${jName} ${jPname}) throws ServiceException {
		return ${jPname}Dao.updateByPrimaryKeySelective(${jPname});
	}
    
    @Override
    public int updateByIdAndResource(${jName} ${jPname}) throws ServiceException {
		return ${jPname}Dao.updateByIdAndResource(${jPname});
	}

	/**
	 * 根据ID修改对象
	 * @param ${jPname}
	 * @return
	 * @throws ServiceException
	 */
	@Override
    public int updateByPrimaryKey(${jName} ${jPname}) throws ServiceException {
		return ${jPname}Dao.updateByPrimaryKey(${jPname});
	}
	/**
	 * 分页查询
	 * @param pageSize
	 * @param pageNumber
	 * @param ${jPname}
	 * @return
	 * @throws ServiceException
	 */
	@Override
	public Page<${jName}> query${jName}Page(Integer pageSize,Integer pageNumber,${jName} ${jPname}) throws ServiceException{
		${jName}Criteria ${jPname}Criteria=new ${jName}Criteria();
		Criteria createCriteria = ${jPname}Criteria.createCriteria();
		if(pageNumber==null||pageNumber<=0){
			pageNumber=1;
		}
		if(pageSize==null||pageSize<=0){
			pageSize=10;
		}
		<#list paramList as param>  
		if(StringUtil.isNotEmpty(${jPname}.get${param["jFname"]}())){
			createCriteria.and${param["jFname"]}EqualTo(${jPname}.get${param["jFname"]}());
		}
		</#list>
		${jPname}Criteria.setOffset((pageNumber-1)*pageSize);
		${jPname}Criteria.setLimit(pageSize);
		List<${jName}> list = ${jPname}Dao.selectByCriteria(${jPname}Criteria);
		long count = ${jPname}Dao.countByCriteria(${jPname}Criteria);
		Page<${jName}> page=new Page<${jName}>(list, count, pageNumber, pageSize);
		return page;
	}
	
	@Override
    public void batchUpdate(List<${jName}> ${jPname}List) throws ServiceException {
		 ${jPname}Dao.batchUpdate(${jPname}List);
	}
	
	<#if (bpmnIsGenerate)>
	protected String warpProcessTaskComment(Boolean approveFlag, String comment) {
		StringBuilder sb = new StringBuilder();
		if (approveFlag) {
			sb.append("审核通过");
		} else {
			sb.append("审核驳回");
		}
		if(!StringUtil.isNotEmpty(comment)){
			comment="";
		}else if(comment.toUpperCase().equals("NULL")){
			comment="";
		}
		if (StringUtil.isNotEmpty(comment)) {
			sb.append("：").append(comment);
		}
		return sb.toString();
	}
    /**
	 * ${jComment}审批流程发起接口
	 * 
	 * @param parameterMap
	 * @return
	 * @throws ServiceException
	 */
	@Override
	@Transactional
	@TxTransaction
	public HashMap<String, Object> startProcess(
			HashMap<String, Object> parameterMap) throws ServiceException{
		// 获取入参start
		Long id = (Long) parameterMap.get("id");
		UaaUser user = (UaaUser) parameterMap.get(CommonProcessRequestParam.CURRENT_USER.getValue());
		
		Map<String, Object> baseParam = new HashMap<>();
		${jName} ${jPname}= ${jPname}Dao.selectByPrimaryKey(id);
		if (${jPname}==null) {
			throw new ServiceException("-1", "${jComment}不存在");
		}
		if (!${jName}StatusEnum.NEW.getValue().equals(${jPname}.getStatus())) {
			throw new ServiceException("-3", "${jComment}状态无效，不能提交审核");
		}
		
		baseParam.put(GlobalVariable.COMPANY_ID.getValue(),${jPname}.getCompanyId());
        baseParam.put(GlobalVariable.PROJECT_ID.getValue(),${jPname}.getProjectId());
        baseParam.put(GlobalVariable.SUB_PROJECT_ID.getValue(),${jPname}.getSubProjectId());
        baseParam.put(GlobalVariable.BUILDING_ID.getValue(),${jPname}.getBuildingId());
        baseParam.put("cancel", false);
        baseParam.put("objectId", id);
        String processId = processService.startProcessTrans(${jPname}.getProjectId(),
				user.getManagerNo(), user.getRealName(),
				ProcessType.${sName}_APPROVAL_PROCESS, "【"+ ${jPname}.get("name") + "】${jComment}审核", baseParam, null);
        ${jPname}.setProcessId(processId);
		${jPname}.setStatus(${jName}StatusEnum.NEW.getValue());
		${jPname}.setModifer(user.getManagerNo());
        ${jPname}.setModifyTime(new Date());
        ${jPname}Dao.updateByPrimaryKeySelective(${jPname});
        return parameterMap;
	}

	/**
	 * 通用${jComment}审批节点
	 * 
	 * @param parameterMap
	 * @return
	 * @throws ServiceException
	 */
	@Override
	@Transactional
	@TxTransaction
	public HashMap<String, Object> checkProcess(
			HashMap<String, Object> parameterMap) throws ServiceException {
		Long id = (Long) parameterMap.get("id");
		String taskId = (String) parameterMap.get("taskId");
		Boolean isApprove = (Boolean) parameterMap.get("isApprove");
		String comment = (String) parameterMap.get("comment");
		comment = warpProcessTaskComment(isApprove, comment);
		UaaUser user = (UaaUser) parameterMap.get(CommonProcessRequestParam.CURRENT_USER.getValue());
		//业务处理
		
		
		Task t = null;
		if (StringUtil.isNotEmpty(taskId)) {
			Map<String, Object> mapTask = new HashMap<String, Object>();
			mapTask.put("taskId", taskId);
			t = processService.getRuTask(mapTask);
		}
		Map<String, Object> processParams = new HashMap<>();
		if (t != null) {
			processParams.put(t.getTaskDefinitionKey()
			+ CommonProcessRequestParam.SUFFIX_IS_APPROVE.getValue(),isApprove ? 1 : 0);
		}
		HashMap<String, Object> nextExecuteParamMap = new HashMap<String, Object>();
		nextExecuteParamMap.put(CommonProcessRequestParam.PROCESS_PARAMS.getValue(),
				processParams);
		nextExecuteParamMap.put(CommonProcessRequestParam.COMMENT.getValue(),
				comment);
		return nextExecuteParamMap;
	}

	/**
	 * ${jComment}审批驳回编辑节点
	 * 
	 * @param parameterMap
	 * @return
	 * @throws ServiceException
	 */
	@Override
	@Transactional
	@TxTransaction
	public HashMap<String, Object> checkReject(
			HashMap<String, Object> parameterMap) throws ServiceException, Exception {
		Long id = (Long) parameterMap.get("id");
		String taskId = (String) parameterMap.get("taskId");
		Boolean isApprove = (Boolean) parameterMap.get(CommonProcessRequestParam.IS_APPROVE.getValue());
		String comment = (String) parameterMap.get("comment");
		StringBuilder sb = new StringBuilder();
		if (isApprove) {
			sb.append("审核通过");
		} else {
			sb.append("审核撤销");
		}
		if (StringUtils.isNotBlank(comment)) {
			sb.append("：").append(comment);
		}
		comment= sb.toString();
		UaaUser user = (UaaUser) parameterMap.get(CommonProcessRequestParam.CURRENT_USER.getValue());	
		// 获取入参end
		Task t = null;
		if (StringUtil.isNotEmpty(taskId)) {
			Map<String, Object> mapTask = new HashMap<String, Object>();
			mapTask.put("taskId", taskId);
			t = processService.getRuTask(mapTask);
		}
		Map<String, Object> processParams = new HashMap<>();
		if (t != null) {
			processParams.put(t.getTaskDefinitionKey()
					+ CommonProcessRequestParam.SUFFIX_IS_APPROVE.getValue(),
					isApprove ? 1 : 0);
		}
		Map<String, Object> baseParam = new HashMap<>();
		${jName} ${jPname}= ${jPname}Dao.selectByPrimaryKey(id);
		if (${jPname}==null) {
			throw new ServiceException("-1", "${jComment}不存在");
		}
		// 修改订单
        if (isApprove) {
            processParams.put("cancel", false);
            BeanUtils.copyProperties(${jPname}, parameterMap);
            ${jPname}.setModifer(user.getManagerNo());
            ${jPname}.setModifyTime(new Date());
       		${jPname}Dao.updateByPrimaryKeySelective(${jPname});
        } else {
            processParams.put("cancel", true);
            // 更新状态为作废状态
            ${jPname}.setStatus(${jName}StatusEnum.DISABLE.getValue());
            ${jPname}.setModifer(user.getManagerNo());
            ${jPname}.setModifyTime(new Date());
       		${jPname}Dao.updateByPrimaryKeySelective(${jPname});
        }
        HashMap<String, Object> nextExecuteParamMap = new HashMap<String, Object>();
        nextExecuteParamMap.put(CommonProcessRequestParam.PROCESS_PARAMS.getValue(),processParams);
        nextExecuteParamMap.put(CommonProcessRequestParam.IS_APPROVE.getValue(), isApprove);
        nextExecuteParamMap.put(CommonProcessRequestParam.COMMENT.getValue(),comment);
        return nextExecuteParamMap;
	}

	/**
	 * ${jComment}统一业务处理方法
	 * 
	 * @param parameterMap
	 * @return
	 * @throws ServiceException
	 */
	@Override
	@Transactional
	@TxTransaction
	public HashMap<String, Object> completeExecuteMethod(
			HashMap<String, Object> parameterMap) throws ServiceException{
		boolean isProcessComplete = (boolean) parameterMap
				.get(CommonProcessRequestParam.IS_PROCESS_COMPLETE.getValue());
		boolean isProcessBusinessApprove = (boolean) parameterMap
				.get(CommonProcessRequestParam.IS_PROCESS_BUSINESS_APPROVE.getValue());
		boolean isApprove = (boolean) parameterMap
				.get(CommonProcessRequestParam.IS_APPROVE.getValue());
		Long id = (Long) parameterMap.get("objectId");
		${jName} ${jPname}= ${jPname}Dao.selectByPrimaryKey(id);
		if (${jPname}==null) {
			throw new ServiceException("-1", "${jComment}不存在");
		}
		if (isProcessComplete) {// 流程完成
			UaaUser user = (UaaUser) parameterMap.get(CommonProcessRequestParam.CURRENT_USER.getValue());
			if (isProcessBusinessApprove) {// 所有节点审核通过，流程结束
				${jPname}.setStatus(${jName}StatusEnum.BYPASSED.getValue());
	            ${jPname}.setModifer(user.getManagerNo());
	            ${jPname}.setModifyTime(new Date());
	       		${jPname}Dao.updateByPrimaryKeySelective(${jPname});
			} else {// 某个节点审批不通过，流程结束
				${jPname}.setStatus(${jName}StatusEnum.NOTPASSED.getValue());
	            ${jPname}.setModifer(user.getManagerNo());
	            ${jPname}.setModifyTime(new Date());
	       		${jPname}Dao.updateByPrimaryKeySelective(${jPname});
			}
		}
		Map<String, String> replaceMap = new HashMap<String, String>();
		String name = ${jPname}.get("name").toString();
		replaceMap.put("${r"${"}name}", name);
		Integer templateType = null;
		String siteNoticeTitle = null;
		String siteNoticeContent = null;
		if (isProcessComplete) {
			if (isApprove) {
				templateType = MailTemplateType.${sName}_PROCESS_APPROVED
						.getTemplateType();
				siteNoticeTitle = name + "${jComment}已通过审批";
				siteNoticeContent = name + "${jComment}流程通过审批，请了解。";
			} else {
				templateType = MailTemplateType.${sName}_PROCESS_REJECT
						.getTemplateType();
				siteNoticeTitle = name + "${jComment}流程驳回";
				siteNoticeContent = name + "${jComment}流程驳回，请及时处理。";
			}
		} else {
			if (isApprove) {
				templateType = MailTemplateType.${sName}_PROCESS_INITIATED
						.getTemplateType();
				siteNoticeTitle = name + "${jComment}流程已发起";
				siteNoticeContent = name + "${jComment}流程已发起，请及时办理。";
			} else {
				templateType = MailTemplateType.${sName}_PROCESS_REJECT
						.getTemplateType();
				siteNoticeTitle = name + "${jComment}流程驳回";
				siteNoticeContent = name + "${jComment}流程驳回，请及时处理。";
			}
		}
		parameterMap.put(CommonProcessRequestParam.MSG_REPLACE_MAP.getValue(),
				replaceMap);
		parameterMap.put(CommonProcessRequestParam.TEMPLATE_TYPE.getValue(),
				templateType);
		parameterMap.put(
				CommonProcessRequestParam.SITE_NOTICE_TITLE.getValue(),
				siteNoticeTitle);
		parameterMap.put(
				CommonProcessRequestParam.SITE_NOTICE_CONTENT.getValue(),
				siteNoticeContent);
		return parameterMap;
	}
			
	</#if>
}